package com.cheetah.start.common.interceptor;

import cn.hutool.core.date.DateUtil;
import com.cheetah.start.common.annotation.ApiCount;
import com.cheetah.start.monitor.apicount.domain.SysApiCount;
import com.cheetah.start.monitor.apicount.service.SysApiCountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * url拦截器
 *
 * @author Feel
 * @Component 要这个才能加载 autowired
 * @date 2021/08/23
 */
@Slf4j
@Component
public class UrlInterceptor implements HandlerInterceptor {

    @Autowired
    private SysApiCountService sysApiCountService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String requestURI = request.getRequestURI();
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        ApiCount annotation = method.getAnnotation(ApiCount.class);
        ApiCount classAnno = method.getDeclaringClass().getAnnotation(ApiCount.class);
        if (annotation != null || classAnno != null) {
            SysApiCount sysApiCount = new SysApiCount();
            sysApiCount.setApi(requestURI)
                    .setApiCount(1)
                    .setApiDay(DateUtil.format(new Date(), "yyyy-MM-dd"))
                    .setCreateTime(new Date());
            sysApiCountService.record(sysApiCount);
        }
        return true;
    }
}
